#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <string.h>
#include <arpa/inet.h>
#include <fcntl.h>


int fd;
struct sockaddr_in serv;

//socket初始化
void socket_init(const char* argv[])
{    
	//1.创建套接字
    fd = socket(AF_INET, SOCK_STREAM, 0);
    if (fd == -1)
    {
		perror("socket error");
		exit(1);
    }

    //2.连接服务器
    struct sockaddr_in serv_addr;
    memset(&serv_addr, 0, sizeof(serv_addr));
    serv_addr.sin_family = AF_INET;
    serv_addr.sin_port = htons(atoi(argv[2]));
    inet_pton(AF_INET, argv[1], &serv_addr.sin_addr.s_addr); //ip地址

    int ret = connect(fd, (struct sockaddr*)&serv_addr, sizeof(serv_addr));
    if (ret ==-1)
    {
		perror("connect error");
		exit(1);
    }
}

int main(int argc, const char* argv[])
{		
	if(argc != 3)
	{
		printf("usage:%s serverip port.\n", argv[0]);
		return -1;
	}

	int value;
	
	socket_init(argv);

    // 通信
    while(1)
    {
		printf("***************************************\n");
		printf("*   1.开灯         2.关灯        3.退出     *\n");
		printf("***************************************\n");
		printf("Please choose:");

		int n;
		scanf("%d", &n);
		getchar();

		switch(n)
		{
			case 1:
				value = 1;
				write(fd, &value, sizeof(value));
				break;
			case 2:
				value = 0;
				write(fd, &value, sizeof(value));
				break;
			case 3:  
				close(fd);	
				exit(0);
				break;
			default:
				printf("Invalid data cmd.\n");	
		}
    }

    close(fd);

    return 0;
}

